package com.talkweb.securitycamera.utils.log;

import com.talkweb.securitycamera.utils.log.interfaces.LogConfig;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilityLifecycleCallbacks;
import ohos.aafwk.ability.AbilityPackage;
import ohos.app.Context;
import ohos.app.ElementsCallback;
import ohos.global.configuration.Configuration;
import ohos.utils.PacMap;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 可通过LogConfig配置hilog和自带的logcat两种打印方式
 * 支持打印位置定位
 */
public class LogUtils {

    private static Context mContext;
    private static LogConfigImpl logConfig = LogConfigImpl.getInstance();
    private static boolean mIsRunningInBackground;

    public static void init(Context context) {
        mContext = context.getApplicationContext();

        initFilePath(mContext);
        catchException(mContext);
        ((AbilityPackage) context).registerCallbacks(new AbilityLifecycleCallbacks() {
            @Override
            public void onAbilityStart(Ability ability) {
                //LogUtils.i("onAbilityStart " + ability.getAbilityName());
            }

            @Override
            public void onAbilityActive(Ability ability) {
                //LogUtils.i("onAbilityActive " + ability.getAbilityName());
            }

            @Override
            public void onAbilityInactive(Ability ability) {
                //LogUtils.i("onAbilityInactive " + ability.getAbilityName());
            }

            @Override
            public void onAbilityForeground(Ability ability) {
                //LogUtils.i("onAbilityForeground " + ability.getAbilityName());
            }

            @Override
            public void onAbilityBackground(Ability ability) {
                //LogUtils.i("onAbilityBackground " + ability.getAbilityName());
            }

            @Override
            public void onAbilityStop(Ability ability) {
                //LogUtils.i("onAbilityStop " + ability.getAbilityName());
            }

            @Override
            public void onAbilitySaveState(PacMap pacMap) {
                //LogUtils.i("onAbilitySaveState ");
            }
        }, new ElementsCallback() {
            @Override
            public void onMemoryLevel(int i) {
                //LogUtils.i("onMemoryLevel " + i);
                if (i == 20) {
                    //app处于后台运行
                    mIsRunningInBackground = true;

                    //日志上报/清除
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            clearDateOverLogData(logConfig.getSaveDay());
                        }
                    }).start();
                } else {
                    mIsRunningInBackground = false;
                }
            }

            @Override
            public void onConfigurationUpdated(Configuration configuration) {
                LogUtils.i("onConfigurationUpdated " + configuration.direction);
            }
        });
    }

    /**
     * 删除逾期日志  建议在非ui线程调用
     * 包含数据库和文件
     *
     * @param dayBefore
     */
    private static void clearDateOverLogData(int dayBefore) {
        clearFileLogData(dayBefore);
    }

    private static void clearFileLogData(int dayBefore) {
        File file = new File(logConfig.getLogDir());
        if (!file.exists()) {
            return;
        }

        long time = dayBefore * 24 * 60 * 60 * 1000L;
        Date date = new Date(new Date().getTime() - time);

        //获取日志文件列表
        File[] listFiles = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File file, String s) {
                if (s.contains("log_")) {
                    return true;
                }

                return false;
            }
        });

        if (listFiles != null && listFiles.length > 0) {
            List<File> fileList = Arrays.asList(listFiles);
            for (int i = fileList.size() - 1; i >= 0; i--) {
                File fileItem = fileList.get(i);
                String name = fileItem.getName();
                i(name);
                if (name.contains("-")) {
                    String nameSub = name.substring(name.indexOf("_") + 1, name.lastIndexOf("."));
                    String[] split = nameSub.split("-");
                    int year = Integer.parseInt(split[0]);
                    int month = Integer.parseInt(split[1]);
                    int day = Integer.parseInt(split[2]);

                    if (date.after(new Date(year, month, day))) {
                        fileItem.delete();
                        i("成功删除文件：log_ " + nameSub);
                    }
                }
            }
        }
    }

    /**
     * 捕获崩溃异常
     *
     * @param context
     */
    private static void catchException(Context context) {
        Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtException(context));
    }

    private static void initFilePath(Context context) {
        String path = context.getFilesDir().getAbsolutePath() + File.pathSeparator + "log";
        logConfig.setDefaultLogDir(path);
    }

    public static class CoreType {
        public final static int CORE_TYPE_LOGCAT = 1;
        public final static int CORE_TYPE_HILOG = 0;

        //        @IntDef({CORE_TYPE_LOGCAT, CORE_TYPE_HILOG})
        @Retention(RetentionPolicy.SOURCE)
        public @interface Type {

        }
    }

    private static AbstractPrinter getPrinter() {
        switch (logConfig.getLogCoreType()) {
            case CoreType.CORE_TYPE_HILOG:
                return Hilogger.getInstance();
            case CoreType.CORE_TYPE_LOGCAT:
                return Logcat.getInstance();
        }

        return null;
    }

    public static LogConfig getLogConfig() {
        return logConfig;
    }

    public static void setTag(String tag) {
        getPrinter().setTag(tag);
    }

//    public static boolean writeToDb(LogEntity entity) {
//        return getPrinter().writeToDb(entity);
//    }
//
//    public static boolean writeToFile(LogEntity entity) {
//        return getPrinter().writeToFile(entity);
//    }

    public static void v(String msg, Object... args) {
        getPrinter().v(msg, args);
    }

    public static void v(Object object) {
        getPrinter().v(object);
    }

    public static void d(String msg, Object... args) {
        getPrinter().d(msg, args);
    }

    public static void d(Object object) {
        getPrinter().d(object);
    }

    public static void i(String msg, Object... args) {
        getPrinter().i(msg, args);
    }

    public static void i(Object object) {
        getPrinter().i(object);
    }

    public static void w(String msg, Object... args) {
        getPrinter().w(msg, args);
    }

    public static void w(Object object) {
        getPrinter().w(object);
    }

    public static void e(String msg, Object... args) {
        getPrinter().e(msg, args);
    }

    public static void e(Object object) {
        getPrinter().e(object);
    }

    public static void json(String json) {
        getPrinter().json(json);
    }
}
